import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { AdInfo, ConfigType } from '../main/type'

const api = {
  settings: (callback: Function) => ipcRenderer.on('settings', (_e, route: string) => callback(route)),
  address: (callback: Function) => ipcRenderer.on('address', (_e, val: AdInfo | undefined) => callback(val)),
  config: (callback: Function) => ipcRenderer.on('config', (_e, val: ConfigType | false) => callback(val)),
  path: (callback: Function) => ipcRenderer.on('path', (_e, val: string) => callback(val)),
  update: (callback: Function) => ipcRenderer.on('update', (_e) => callback()),
  edge: (callback: Function) => ipcRenderer.on('edge', (_e, edge: 'n' | 'l' | 'r') => callback(edge)),
  mouseover: (val: boolean) => ipcRenderer.send('mouseover', val),
}

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
